//
//  BYWebVC.m
//  ZhiHuiLiJiang
//
//  Created by 胡忠诚 on 2018/11/19.
//  Copyright © 2018 WisdomLijiang. All rights reserved.
//webView的控制器

#import "BYWebVC.h"
#import "BYLoginVC.h"//登录的VC

@interface BYWebVC ()<BYWebViewDelegate>
/**通用的WebView*/
@property (nonatomic, strong)BYWebView *webView;

@property (nonatomic, strong)UIButton *backbtn;


@end
@implementation BYWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
     [self initWebView];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
    if (!self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = YES;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)initWebView{
    self.view.backgroundColor = [UIColor whiteColor];
    _webView = [[BYWebView alloc] initWithFrame:CGRectMake(0, BY_StatusBar_H, BY_ScreenWidth, BY_ScreenHeight-BY_StatusBar_H -BY_Bot_H)];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    [self loadWebViewUrl];
    self.backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backbtn.frame = CGRectMake(KSCREEWIDTH - 36, BY_StatusBar_H+10, 24, 24);
    [self.backbtn setBackgroundImage:[UIImage imageNamed:@"closeBtnIcon"] forState:UIControlStateNormal];
    [self.backbtn addTarget:self action:@selector(backbtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backbtn];

}

#pragma mark - 进度条及webView代理
- (void)loadWebViewUrl{
    //加载h5页
    if ([_url hasPrefix:@"http"]) {//是http开头的--才加载
        NSString *webURL= @"";
        
        NSURL *testURL = [NSURL URLWithString:_url];
        if (![self willGotoOutSideWebViewByKey:@"userid=" observerUrl:testURL] && ![self willGotoOutSideWebViewByKey:@"&token=" observerUrl:testURL]) {//如果url里没有userid和token那么就添加这俩字段
            NSString *paramStr = [NSString stringWithFormat:@"userid=%@&token=%@",[SaveCacheData loadDataStrWithKey:currentUserudid] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserudid],[SaveCacheData loadDataStrWithKey:currentUserToken] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserToken]];
            if ([_url rangeOfString:@"?"].location == NSNotFound) {//没有?参数
                webURL = [NSString stringWithFormat:@"%@?%@",_url,paramStr];
            } else {//有参数
                webURL = [NSString stringWithFormat:@"%@&%@",_url,paramStr];
            }
        }else{//否则就不用管了
            webURL = _url;
        }
        NSString *encodedUrl = [webURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *requestUrl = [NSURL URLWithString:encodedUrl];
        NSLog(@"----web页----%@",encodedUrl);
        NSURLRequest *request =[NSURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];//缓存策略：如果服务器有变化就请求，没有用本地缓存；NSURLRequestReloadIgnoringLocalAndRemoteCacheData 忽略所有缓存
        [_webView loadRequest:request];
    }else{
        //提示错误
    }
}
- (void)webView:(BYWebView *)webView didFailLoadWithError:(NSError *)error{
//    if ([Utility getNetworkType] == NETWORK_TYPE_NONE) {
//        [MBProgressHUD showMessage:@"网络不给力 请稍后再试" MBPMode:5 isWindiw:YES];
//    }else{
//        [MBProgressHUD showMessage:@"加载失败!" MBPMode:5 isWindiw:YES];
//    }
}
-(void)webViewDidFinishLoad:(BYWebView *)webView{
    NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
    // 设置localStorage
    NSString *token = [NSString stringWithFormat:@"localStorage.setItem('token', '%@')",[SaveCacheData loadDataStrWithKey:currentUserToken] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserToken]];
    NSString *userid = [NSString stringWithFormat:@"localStorage.setItem('userid', '%@')",[SaveCacheData loadDataStrWithKey:currentUserudid] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserudid]];
    NSString *latitude = [NSString stringWithFormat:@"localStorage.setItem('latitude', '%@')",[useDef objectForKey:@"latitude"]];
    NSString *longitude = [NSString stringWithFormat:@"localStorage.setItem('longitude', '%@')",[useDef objectForKey:@"longitude"]];
//    NSLog(@"ddddddddddddd---userid:%@---token:%@",userid,token);
    [self.webView evaluateJavaScript:userid completionHandler:nil];
    [self.webView evaluateJavaScript:latitude completionHandler:nil];
    [self.webView evaluateJavaScript:longitude completionHandler:nil];
    [self.webView evaluateJavaScript:token completionHandler:nil];

}
- (BOOL)webView:(BYWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = [request URL];
    NSLog(@"shouldStartLoadWithRequest = %@", [url absoluteString]);
    //跳转到原生控制器
    if (![[SaveCacheData loadDataStrWithKey:loginState] isEqualToString:@"YES"]) {
        if (YES == [self willGotoOutSideWebViewByKey:@"jumpFDlink=iosAPPLogin" observerUrl:url]) {//@"biyu6-xxxxx"为测试跳转字段
            BYLoginVC *loginVC = [[BYLoginVC alloc]init];
            [self presentViewController:[[UINavigationController alloc] initWithRootViewController:loginVC] animated:YES completion:nil];
            loginVC.loginComplete = ^{//登录后的跳转等操作
                NSLog(@"H5页调用原生登录后的回调:%@",self.url);
//                [webView reload];
                [self loadWebViewUrl];//重新加载web页
            };
            return NO;
        }
    }
    return YES;
}
- (BOOL)willGotoOutSideWebViewByKey:(NSString *)key observerUrl:(NSURL *)url {//判断url是否包含字符串key
    if (nil != url) {
        NSRange _rang = [[url absoluteString] rangeOfString:key];
        if(_rang.length > 0 && _rang.location != NSNotFound) {
            return YES;
        }
    }
    return NO;
}
-(void)backbtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
